const { DataTypes } = require('sequelize')

module.exports = (sequelize) => {
  const DynamicMenu = sequelize.define('DynamicMenu', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    name: {
      type: DataTypes.STRING,
      allowNull: false,
      comment: '菜单名称'
    },
    key: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
      comment: '菜单唯一标识'
    },
    icon: {
      type: DataTypes.STRING,
      allowNull: true,
      comment: '菜单图标'
    },
    table_name: {
      type: DataTypes.STRING,
      allowNull: false,
      comment: '对应的数据库表名'
    },
    description: {
      type: DataTypes.STRING,
      allowNull: true,
      comment: '菜单描述'
    },
    permissions: {
      type: DataTypes.JSON,
      allowNull: true,
      defaultValue: ['read', 'create', 'update', 'delete'],
      comment: '菜单权限列表'
    },
    columns_config: {
      type: DataTypes.JSON,
      allowNull: true,
      comment: '表格列配置'
    },
    sort_order: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: '排序顺序'
    },
    status: {
      type: DataTypes.ENUM('active', 'inactive'),
      allowNull: false,
      defaultValue: 'active',
      comment: '菜单状态'
    },
    created_by: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'users',
        key: 'id'
      },
      comment: '创建者'
    },
    created_at: {
      type: DataTypes.DATE,
      defaultValue: DataTypes.NOW
    },
    updated_at: {
      type: DataTypes.DATE,
      defaultValue: DataTypes.NOW
    }
  }, {
    tableName: 'dynamic_menus',
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: 'updated_at',
    comment: '动态菜单配置表'
  })

  // 关联关系
  DynamicMenu.associate = (models) => {
    DynamicMenu.belongsTo(models.User, {
      foreignKey: 'created_by',
      as: 'creator'
    })
  }

  return DynamicMenu
}
